package com.am.mosl.cityandroid.login;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import com.am.mosl.cityandroid.R;
import com.am.mosl.cityandroid.activity.BaseActivity;
import com.am.mosl.cityandroid.constant.HttpConstant;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author 邓思宇 输入验证码界面
 * 
 */

public class VertifyActivity extends BaseActivity {

	private EditText vertifyNum;
	private Button next;
	private Button reVertify;
	private TextView msg;
	private String phoneNum;
	private String verifyNum;
	private ProgressDialog mDialog;
	private String FLAG;
	private int flag = 0;// 判断验证码是否正确而立的flag
	public static Handler h;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				int i = msg.arg1;
				reVertify.setText("重发验证码（" + i + "）");
				if (i == 0) {
					reVertify.setEnabled(true);
					reVertify.setText("重发验证码");
				}
				break;

			case 2:
				if (flag == 0) {
					mDialog.dismiss();
					Toast.makeText(VertifyActivity.this, "验证码错误",
							Toast.LENGTH_SHORT).show();
					break;
				} else if (flag == 1) {
					mDialog.dismiss();
					// 打开下一个界面 为注册用户界面 传送手机号码 还有验证码？？？

					if (FLAG.equals("0")) {

						Intent intent = new Intent(VertifyActivity.this,
								RecodeActivity.class);
						intent.putExtra("Phone", phoneNum);
						intent.putExtra("Verify", verifyNum);
						startActivity(intent);

					} else if (FLAG.equals("1")) {

						Intent intent = new Intent(VertifyActivity.this,
								NewAccountActivity.class);
						intent.putExtra("Personal", "0");
						intent.putExtra("Phone", phoneNum);
						intent.putExtra("Verify", verifyNum);
						startActivity(intent);
					}

				}

				break;

			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.z_vertify_activity);

		initBar();
		
		h = new Handler() {
	        public void handleMessage(Message msg) {
	            super.handleMessage(msg);

	            switch(msg.what) {

	            case 0:
	                finish();
	                break;

	            }
	        }

	    };
	    
	    

		msg = (TextView) findViewById(R.id.msg1);
		reVertify = (Button) findViewById(R.id.vertify);
		next = (Button) findViewById(R.id.vertify_next);
		vertifyNum = (EditText) findViewById(R.id.VertifyNum);

		// 获取到上一个页面得来的手机号码值
		Bundle extras = getIntent().getExtras();
		phoneNum = extras.getString("Phone");
		FLAG = extras.getString("FLAG");
		msg.setText("您的手机号：" + phoneNum);

		
		reVertify.setEnabled(false);
		// 设定暂停六十秒
		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				for (int i = 60; i > -1; i--) {
					try {
						Message message = new Message();
						message.arg1 = i;
						message.what = 1;
						mHandler.sendMessage(message);
						Thread.sleep(1000);

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
		
		
		// 点击下一步按钮
		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				String verifynum = vertifyNum.getText().toString().trim();
				if (verifynum.equals("")) {
					Toast.makeText(VertifyActivity.this, "验证码不能为空",
							Toast.LENGTH_SHORT).show();
					return;
				}

				verify(verifynum);

			}
		});

		// 点击获取验证码按钮
		reVertify.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				reVertify.setEnabled(false);

				// 设定重新发送验证码

				if (isNetworkAvailable(VertifyActivity.this)) {

					mDialog = ProgressDialog.show(VertifyActivity.this, "",
							"正在发送验证码...", true);

					FinalHttp finalHttp = new FinalHttp();
					AjaxParams params = new AjaxParams();
					params.put("telephone", phoneNum);
					finalHttp.post(HttpConstant.GetVerifyCode, params,
							new AjaxCallBack<Object>() {
								@Override
								public boolean isProgress() {
									return super.isProgress();
								}

								@Override
								public void onSuccess(Object o) {
									super.onSuccess(o);
									try {
										JSONObject jsonObject = new JSONObject(
												o.toString());
										String status = (String) jsonObject
												.opt("status");
										String msg = (String) jsonObject
												.opt("msg");
								
										if (mDialog != null) {
											mDialog.dismiss();
										}
										
										if (status.equals("1")) {

										} else {

											Toast.makeText(VertifyActivity.this,
													" 发送失败：" + msg,
													Toast.LENGTH_SHORT).show();

											return;

										}

									} catch (JSONException e) {
										e.printStackTrace();
									}
								}
							});

				} else {
					Toast.makeText(VertifyActivity.this, "网络未连接",
							Toast.LENGTH_SHORT).show();
				}

				// 设定暂停六十秒
				new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						for (int i = 60; i > -1; i--) {
							try {
								Message message = new Message();
								message.arg1 = i;
								message.what = 1;
								mHandler.sendMessage(message);
								Thread.sleep(1000);

							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}.start();

			}
		});

	}

	/**
	 * 判断网络是否可用
	 * 
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager mgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 判断验证码是否正确
	 * 
	 */
	public boolean verify(final String v) {

		if (isNetworkAvailable(VertifyActivity.this)) {

			mDialog = ProgressDialog.show(VertifyActivity.this, "",
					"正在判断验证码是否正确...", true);

			FinalHttp finalHttp = new FinalHttp();
			AjaxParams params = new AjaxParams();
			params.put("telephone", phoneNum);
			finalHttp.post(HttpConstant.SelectVerifyCode, params,
					new AjaxCallBack<Object>() {
						@Override
						public boolean isProgress() {
							return super.isProgress();
						}

						@Override
						public void onSuccess(Object o) {
							super.onSuccess(o);
							try {
								JSONObject jsonObject = new JSONObject(o
										.toString());
								String status = (String) jsonObject
										.opt("status");
								String msg = (String) jsonObject.opt("msg");
								String verifycode = (String) jsonObject
										.opt("verifycode");

								verifyNum = verifycode;

								if (v.equals(verifycode)) {
									flag = 1;
								} else {
									flag = 0;
								}

								Message message = new Message();
								message.what = 2;
								mHandler.sendMessage(message);

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					});

		} else {
			Toast.makeText(VertifyActivity.this, "网络未连接", Toast.LENGTH_SHORT)
					.show();
		}

		if (flag == 1) {
			return false;
		}
		return true;
	}

	private void initBar() {

		TextView title = (TextView) findViewById(R.id.tittle);
		title.setText("填写验证码");

		View right_title = (TextView) findViewById(R.id.right_tittle);
		right_title.setVisibility(View.GONE);
	}
	

	// 点击返回
	public void BackToBack(View view) {
		this.finish();
	}

}